#!/usr/bin/env python
# -*- conding : UTF-8 -*-
#0.5.2@2007-08-03
import sys, time, os, shutil, popen2
import pdb
def readarg():
    argus = 0
    for i in sys.argv:
        if i == '-old' or i == '-D':
            argus = 1
    return argus
    print "++++++++++",
    print argus
def valueset( dp ):
    global d, drml, ckdrm, wkph
    wkph = os.getenv( "HOME" ) + os.sep + "CD"      #set the work path
    drml = wkph + os.sep + "drm.cdifo"        #the drm path.
    if dp:
        d = "/dev/sr1"
    elif not dp:
        d = "/dev/sr0"      #the path of target Disc.
    else:
        print >> sys.stderr, "Logic Error!!!\nProgram connt run!\n--------------------------------------------------\nExit!!!"
        sys.exit(1)
    stdout, stdin = popen2.popen2( "df" )       #read the target disk's path from "df"
    stdoutd = stdout.read()
    stdout.close()
    stdin.close()
    out=stdoutd.splitlines()
    for i in out:
        x=i.find( d )
        x+=1
        if x:
            ii=i.split()
            d=ii[-1]
    ckdrm = 0       #record the drm file that is read already ?
def mk_drm( nnum = 0 ):
            #nnum is the parameter for input the Disc No..
    num = nnum + 1
    numn = "cdn0-" + str(num)       #the new Disc No..
    drmf = numn + '\n=================================================================================\n'     #separat line
    drm = open( drml, "w" )
    print>> drm, "%c%c%c" % (0xEF, 0xBB, 0xBF),     
    print >> drm, drmf.decode('utf-8')
    drm.close()     #make the new drm.cdifo
#    print 'The New cdifo No. is:_',
 #   print numn
def mk_cdd( old = 0 ):
    global nu, drmf, cddrm
    if old:
        try:        #try to open the drm file in disk (writen before)
            drm =  open( drml )
        except IOError, message:
            print >> sys.stderr, 'The old drm file not correct!\nPlease Check!'
            sys.exit(1)
    elif not old:
        try:        #try to open the drm file in the Disc
            drm = open( d + os.sep + 'drm.cdifo' )
        except IOError, message:
            print >> sys.stderr, 'Did not find the Disc!\nPlease input the target Disc.'        #if this program can not find the drm file, print an error!
            sys.exit(1)     #exit with error
    else:
        print >> sys.stderr, "Logic Error!!!\nProgram connt run!\n--------------------------------------------------\nExit!!!"
        sys.exit(1)
    drm.read(4)
    nu = str(drm.readline(10))     #read the drm file, read the Disc No. from it
    drmf = drm.read()       #read the whole drm file.
    drm.close()
    ck_cdd( wkph + os.sep, nu )     #check if it already has the same name base file.
    print 'check base ---\nOK!'
    stdout, stdin = popen2.popen2( "ls -R " + d )       #use system command "ls" to read whole Disc file list.
    cdfile = stdout.read()
    stdout.close()
    stdin.close()
    nowday = str(time.localtime()[0]) + "Y  " + str(time.localtime()[1]) + "N  " + str(time.localtime()[2]) + "D   @" + str(time.localtime()[3]) + " - " + str(time.localtime()[4]) + " - " + str(time.localtime()[5])       #time record
    cddrm = nu + '\nThis CD make @ ' + nowday + "\n" + cdfile + "\n\n\n" + drmf
    return cddrm        #return the Disc data
def ck_cdd( path="", fn="" ):
        if os.path.isfile( path + "CDD" + os.sep + fn ):        #check is it that has a same name file in the base
            shutil.move( path + "CDD" + os.sep + fn, path + fn )        #if it already has a same name file in the base, move it to work path.
            print 'find a same name file, move it to ' + wkph + "."
        else:
            pass        #if not, do nothing
def writebase():
    cdbasef = open( wkph + os.sep + "CDD" + os.sep + nu, "w" )       #write the data to base
    # print >>cdbasef, "%c%c%c" % (0xEF, 0xBB, 0xBF), 
    print >> cdbasef, cddrm
    print 'write base data ---\nOK!'
    cdbasef.close()
def show_no():
    nofl = open( wkph + os.sep + nu + "__Finish!", w )
    print >> nofl, nu
    nofl.close()
def main():
#    valueset()
    argus = readarg()
    print argus
    if argus:
        valueset( 1 )
        print 'initializes ---\nOK!\nGo on.'
        print 'the disc in: ' + d
        mk_cdd( 1 )
    elif not argus:
        valueset( 0 )
        print 'initializes ---\nOK!\nGo on.'
        print 'the disc in: ' + d
        mk_cdd( 0 )     
    else:
        print >> sys.stderr, "Logic Error!!!\nProgram connt run!\n--------------------------------------------------\nExit!!!"
        sys.exit(1)
#    os.system( "rm -f " + wkph + os.sep + "finish_*" )
#    print 'clear the old finish file'
    print 'make the disc data ---\nOK!'
    writebase()
    print 'write data to base ---\nOK!'
#    print 'nu is :'
#    print nu
    pdb.set_trace()
    nua = int(nu[4:9])
#    print 'nua is:'
#    print nua
    mk_drm( nua )
    print 'make the new drm file ---\nOK!'
    print '================'
    print 'Disc:_' + nu
    print '================\nOK!'
if __name__ == '__main__':
    print 'by RAh-XePhON \n @ http://ToKyo-JuPiTer.Blogspot.com/'
    main()
    print 'Finish!\nExit!'
    sys.exit(0)
